import fileio from '@ohos.file.fs';
import zlib from '@ohos.zlib';

function format(date: Date, str: string): string {
  let obj = {
    yyyy: date.getFullYear(),
    yy: ('' + date.getFullYear()).slice(-2),
    M: date.getMonth() + 1,
    MM: ('0' + (date.getMonth() + 1)).slice(-2),
    d: date.getDate(),
    dd: ('0' + date.getDate()).slice(-2),
    H: date.getHours(),
    HH: ('0' + date.getHours()).slice(-2),
    h: date.getHours() % 12,
    hh: ('0' + date.getHours() % 12).slice(-2),
    m: date.getMinutes(),
    mm: ('0' + date.getMinutes()).slice(-2),
    s: date.getSeconds(),
    ss: ('0' + date.getSeconds()).slice(-2),
    w: ['日', '一', '二', '三', '四', '五', '六'][date.getDay()]
  };
  return str.replace(/([a-z]+)/ig, function ($1) {
    return obj[$1]
  });
}

export class FileIOUtil {
  fd: number = 0
  private filePath: string = ''
  private baseDir: string = '' //沙箱路径
  private logDir: string = ''

  constructor(dir: string) {
    this.baseDir = dir
    this.logDir = dir + "/filelog"
    try {
      fileio.mkdirSync(this.logDir, true)
    } catch (e) {
    }
    this.open()
  }

  async zip(): Promise<string> {

    try {
      let outzip = this.baseDir + '/log.zip'
      await zlib.compressFile(this.logDir, outzip, {
        level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION,
        memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT,
        strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY
      })
      return outzip
    } catch (e) {
      console.log("file", JSON.stringify(e))
    }
    return ""
  }

  write(msg: string) {
    try {
      if (this.fd < 0) {
        return
      }
      let content = this.getTime() + msg
      fileio.write(this.fd, `${content}\n`);
    } catch (e) {
    }

  }

  clean() {
    //保留最近5天的文件
    let time = Date.now() / 1000 - 60 * 60 * 24 * 5
    fileio.listFile(this.logDir).then(files => {
      console.log("file==", JSON.stringify(files), files.length)
      files?.forEach(item => {
        try {
          let file = this.logDir + "/" + item
          let stat = fileio.statSync(file)
          // console.log("file==", JSON.stringify(files), files.length, stat.mtime)
          if (stat.mtime < time) {
            fileio.unlink(file)
          }
        } catch (e) {
        }

      })
    })
  }

  private close() {
    try {
      fileio.closeSync(this.fd)
      this.fd = -1
    } catch (e) {
    }
  }

  private open() {
    this.filePath = this.logDir + '/' + format(new Date(), 'yyyy-MM-dd') + '.txt'
    let fl = fileio.openSync(this.filePath, fileio.OpenMode.CREATE | fileio.OpenMode.READ_WRITE)
    this.fd = fl.fd;
  }

  private getTime() {
    return format(new Date(), 'yyyy-MM-dd HH:mm:ss')
  }
}